import { getAssetsStatus } from '@/services/ant-design-pro/api';
import type { ActionType, ProColumns, ProDescriptionsItemProps } from '@ant-design/pro-components';
import {

  PageContainer,
  ProDescriptions,
  ProTable,
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Badge, Drawer, message } from 'antd';
import React, { useRef, useState, useEffect } from 'react';
// import dayjs from 'dayjs';
import { fetchAssetsData } from '../../../utility/fetchcategoryforselect';
const TableList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  //是否显示详细的物品信息
  const [showDetail, setShowDetail] = useState<boolean>(false);
  //选中行的数据，用于点击某一行数据的sn号显示详细信息
  const [currentRow, setCurrentRow] = useState<API.AssetsStatusListItem>();

  const [assetsclass, setAssetsClass] = useState<{ [key: string]: { text: string } }>({});
  const [assetsname, setAssetsName] = useState<{ [key: string]: { text: string } }>({});
  const [assetoutboundtype, setAssetOutboundType] = useState<{ [key: string]: { text: string } }>({});
  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();
  const [, contextHolder] = message.useMessage();

  // 抽取格式化函数，统一功能，转成valueEnum的格式
  const formatValueEnum = (data: any[]) => {
    return data.reduce((acc, item) => {
      acc[item.value] = { text: item.label };
      return acc;
    }, {} as { [key: string]: { text: string } });
  };


  useEffect(() => {
    const loadData = async () => {
      // 获取两个类别的数据  1为资产类别，7为物品类别,2为出库类别
      const [assetsclassdata, assetnamedata, assetoutbounddata] = await Promise.all([
        fetchAssetsData(1),
        fetchAssetsData(7),
        fetchAssetsData(2),
      ]);

      // 更新状态  
      setAssetsClass(formatValueEnum(assetsclassdata));
      setAssetsName(formatValueEnum(assetnamedata));
      setAssetOutboundType(formatValueEnum(assetoutbounddata));
    };
    loadData();
  }, []);


  /*
  const { run: delRun, loading } = useRequest(...): 这里使用了解构赋值。
run: 这是 useRequest 返回的一个函数，用于触发请求。
delRun: 这是将 run 重命名为 delRun，以便更清楚地表示这是一个用于删除操作的函数。
loading: 这是一个布尔值，指示请求是否正在进行中。你可以使用这个值来显示加载状态（例如，禁用按钮或显示加载指示器）。
  */


  const columns: ProColumns<API.AssetsStatusListItem>[] = [
    {
      title: (
        <FormattedMessage
          id="pages.assets.class"
          defaultMessage="assetsclass"
        />
      ),
      dataIndex: 'assetsclass',
      valueEnum: assetsclass

    },
    {
      title: <FormattedMessage id="pages.assets.name" defaultMessage="assetsname" />,
      dataIndex: 'assetsname',
      valueEnum: assetsname

    },
    {
      title: (
        <FormattedMessage
          id="pages.assets.sn"
          defaultMessage="assetssn"
        />
      ),
      dataIndex: 'sn',
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);//
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },

    },
    {
      title: <FormattedMessage id="pages.assets.number" defaultMessage="assetsnumber" />,
      dataIndex: 'assetsnumber',

    },
    {
      title: (
        <FormattedMessage
          id="pages.assets.type"
          defaultMessage="assetstype"
        />
      ),

      dataIndex: 'type',
      search: false,//不开启查询功能
    },
    {
      title: (
        <FormattedMessage
          id="pages.assets.storagetime"
          defaultMessage="storagetime"
        />
      ),
      dataIndex: 'purchasetime',
      valueType: 'date',
      sorter: true,
      search: false,//不开启查询功能
      // renderText: (text) => {  
      //   // 将 text 断言为 string  
      //   const stringText = text as string; 
      //        // 检查 stringText 是否为有效字符串  
      //   if (stringText === '0001-01-01T00:00:00') {  
      //     return null; // 如果是无效日期，返回 null  
      //   }  
      //  else{
      //   const t=stringText.split("T")[0];  
      //   console.log(t)
      //   return stringText.split("T")[0];  
      //  }
      // },  
    },

    {
      title: (
        <FormattedMessage
          id="pages.assets.calinterval"
          defaultMessage="calinterval"
        />
      ),
      dataIndex: 'calinterval',
      sorter: true,
      search: false,//不开启查询功能
    },
    {
      title: (
        <FormattedMessage
          id="pages.assets.lastoutboundtype"
          defaultMessage="lastoutboundtype"
        />
      ),
      dataIndex: 'lastoutboundtype',
      valueEnum: assetoutboundtype,


    },
    {
      title: (
        <FormattedMessage
          id="pages.assets.borrower"
          defaultMessage="borrower"
        />
      ),
      dataIndex: 'borrower',
      sorter: true,
    },
    {
      title: (
        <FormattedMessage
          id="pages.assets.project"
          defaultMessage="project"
        />
      ),
      dataIndex: 'project',
      sorter: true,
    },
    {
      title: (
        <FormattedMessage
          id="pages.assets.vehicle"
          defaultMessage="vehicle"
        />
      ),
      dataIndex: 'vehicle',
      sorter: true,
    },

    {
      title: (
        <FormattedMessage
          id="pages.assets.lastoutboundtime"
          defaultMessage="lastoutboundtime"
        />
      ),
      dataIndex: 'lastoutboundtime',
      valueType: 'date',
      sorter: true,
      search: false,//不开启查询功能
      renderText(text) {
        return text === "0001-01-01T00:00:00" ? null : text;
      },
    },
    {
      title: (
        <FormattedMessage
          id="pages.assets.lastinboundtime"
          defaultMessage="lastinboundtime"
        />
      ),
      dataIndex: 'lastinboundtime',
      valueType: 'date',
      sorter: true,
      search: false,//不开启查询功能
      renderText(text) {
        return text === "0001-01-01T00:00:00" ? null : text;
      },
    },
    {
      title: (
        <FormattedMessage
          id="pages.assets.sraptime"
          defaultMessage="scraptime"
        />
      ),
      dataIndex: 'scraptime',
      valueType: 'date',
      sorter: true,
      search: false,//不开启查询功能
    },
    {
      title: (
        <FormattedMessage
          id="pages.assets.status"
          defaultMessage="status"
        />
      ),
      dataIndex: 'status',
      sorter: true,
      valueEnum: {  
        '在库': { text: '在库', status: 'success' },  
        '出库': { text: '出库', status: 'warning' },  
        '报废': { text: '报废', status: 'error' },  
      },  
      renderText(text) {
        return text === "报废" ? <Badge status='error' text={text}/> : text === "出库" ?<Badge status='warning' text={text}/> :<Badge status='success' text={text}/>;
      },

    },



  ];

  return (
    <PageContainer>
      {contextHolder}
      <ProTable<API.AssetsStatusListItem, API.PageParams>
        headerTitle={intl.formatMessage({
          id: 'pages.assetsstatus.title',
          defaultMessage: '总资产状态表',
        })}
        actionRef={actionRef}
        rowKey="sn"
        search={{
          labelWidth: 120,
        }}
        // toolbar={}
        request={getAssetsStatus}
        columns={columns}

      />


      {/* 这是点击sn号出现的物品详细说明抽屉页面 */}
      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.sn && (
          <ProDescriptions<API.AssetsStatusListItem>
            column={2}
            title={currentRow?.sn}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.sn,
            }}
            columns={columns as ProDescriptionsItemProps<API.AssetsStatusListItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
